<!-- 话单记录 -->
<template>
	<a-card v-if="props.viewType === 'total'">
		<a-form ref="searchFormRef" name="advanced_search" :model="searchFormState" class="ant-advanced-search-form">
			<a-row :gutter="24">
				<a-col :span="6">
					<a-form-item label="主叫号码" name="caller">
						<a-input v-model:value="searchFormState.caller" placeholder="请输入主叫号码" enter-button
								 allowClear/>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="被叫号码" name="callee">
						<a-input v-model:value="searchFormState.callee" placeholder="请输入被叫号码" enter-button
								 allowClear/>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="坐席账号" name="userName">
						<a-input v-model:value="searchFormState.userName" placeholder="请输入坐席账号" enter-button
								 allowClear/>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="任务ID" name="taskId">
						<a-input v-model:value="searchFormState.taskId" placeholder="请输入任务ID" enter-button
								 allowClear/>
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="24">
				<a-col :span="6">
					<a-form-item label="通话时长" name="callDuration">
						<a-input
							v-model:value="searchFormState.callDuration"
							placeholder="请输入通话时长"
							enter-button
							allowClear
						/>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="回传时间">
						<a-range-picker
							v-model:value="createTimeArr"
							@change="dateChange"
							:default-value="[dayjs('2024-11-11', 'YYYY-MM-DD'), dayjs('2024-11-15', 'YYYY-MM-DD')]"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="通话类型" name="callType">
						<a-select
							v-model:value="searchFormState.callType"
							placeholder="请选择通话类型"
							:options="callTypeOptions"
							allowClear
						/>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="呼叫序列号" name="callDuration">
						<a-input v-model:value="searchFormState.callId" placeholder="请输入呼叫序列号" enter-button
								 allowClear/>
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="24">
				<a-col :span="6">
					<a-form-item label="所属公司" name="deptId">
						<a-tree-select
							v-model:value="searchFormState.deptId"
							class="xn-wd"
							:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
							placeholder="请选择组织"
							allow-clear
							tree-default-expand-all
							:tree-data="treeData"
							:tree-default-expanded-keys="treeDefaultExpandedKeys"
							:field-names="{
								children: 'children',
								label: 'name',
								value: 'id'
							}"
						></a-tree-select>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-button type="primary" @click="tableRef.refresh(true)">查询</a-button>
					<!--					<a-button type="primary" @click="sendMessage">发送</a-button>-->
					<a-button style="margin: 0 8px" @click="reset">重置</a-button>
				</a-col>
			</a-row>
		</a-form>
	</a-card>
	<a-card>
		<s-table
			ref="tableRef"
			:size="pageOptions.size"
			:pageSizeOptions="pageOptions.sizeOptions"
			:columns="columns"
			:data="loadData"
			:row-key="(record) => record.id"
			:scroll="{ x: 'max-content' }"
		>
			<template #asrName="{ text }">
				<span v-if="text === '识别失败'">无彩铃</span>
				<span v-else>{{ text }}</span>
			</template>
			<template #signal="{ text }">
				<span v-if="text === 2">是</span>
				<span v-else>否</span>
			</template>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'fileUrl' && record.fileUrl != null && record.fileUrl !== ''">
					<a-space>
						<a-button type="link" size="small" @click="toPlay(record)">播放</a-button>
					</a-space>
				</template>
			</template>
		</s-table>
	</a-card>
	<xn-form-container title="录音播放" :width="1000" :visible="visible" :destroy-on-close="true" @close="onClose">
		<div class="call-autio mb-5">
			<div class="voice">
				<WaveSurferAudio :audio-url="audioUrl" @timeUpdate="handleTimeUpdate"></WaveSurferAudio>
			</div>
			<!-- <Audio :audioUrl="audioUrl" :isStop="isStop" /> -->
			<div class="btn">
				<div v-if="voiceStatus === ''">
					<a-radio-group
						v-model:value="voiceStatus"
						button-style="solid"
						@change="voiceStatusChange"
						:disabled="!isQualityRole"
					>
						<a-radio-button value="normal">合格</a-radio-button>
						<a-radio-button value="abnormal">违规</a-radio-button>
					</a-radio-group>
					<a-popover trigger="hover" placement="topRight">
						<template #content>
							<span>质检内容不允许重复修改，请务必谨慎操作！</span>
						</template>
						<ExclamationCircleOutlined class="ml-3"/>
					</a-popover>
				</div>
				<i v-if="voiceStatus === 'abnormal'" class="iconfont icon-buhege"></i>
				<i v-if="voiceStatus === 'normal'" class="iconfont icon-hege"></i>
				<a-button v-if="voiceStatus === 'abnormal'" type="link" primary @click="abnormalCheck">违规详情
				</a-button>
			</div>
		</div>
		<!-- 仿微信聊天记录 -->
		<div class="call-chat">
			<a-spin :spinning="chatLoading">
				<ChatWindow
					ref="chatWindowRef"
					:current-user="currentUser"
					:target-user="targetUser"
					:messages="messages"
					:curMsgId="curMsgId"
				/>
			</a-spin>
		</div>
		<!-- <ChatWindow :current-user="currentUser" :target-user="targetUser" :messages="messages" /> -->
	</xn-form-container>
	<!-- 质检异常弹框 -->
	<a-modal
		v-model:open="modalOpen"
		title="违规详情"
		ok-text="确认"
		cancel-text="取消"
		:ok-button-props="{ disabled: isAbnormaled }"
		:cancel-button-props="{ disabled: isAbnormaled }"
		@ok="okModal"
		@cancel="cancelModal"
	>
		<a-form ref="checkFormRef" :model="formState" :rules="rules">
			<a-form-item label="类型" name="inspection">
				<a-select v-model:value="formState.inspection" placeholder="请选择违规类型" :disabled="isAbnormaled">
					<a-select-option v-for="item in manualCheck" :key="item.value" :value="item.value">{{
							item.label
						}}
					</a-select-option>
				</a-select>
			</a-form-item>
			<a-form-item label="备注" name="remark">
				<a-textarea
					v-model:value="formState.remark"
					placeholder="请输入违规详情"
					:auto-size="{ minRows: 2, maxRows: 5 }"
					:disabled="isAbnormaled"
				/>
			</a-form-item>
		</a-form>
	</a-modal>
</template>

<script setup name="ReceiptRecord">
import manualCheckApi from '@/api/qc/manualCheck/manualCheckApi'
import dayjs from 'dayjs'
import tool from '@/utils/tool'
import bizUserApi from '@/api/biz/bizUserApi'
//仿微信聊天记录
import {ref} from 'vue'
// import ChatWindow from '@/views/qc/voice/chat/ChatWindow.vue'
import voiceTextApi from '@/api/qc/voice/text/voiceTextApi'
import callReceiptApi from '@/api/tjzy/call/receipt/callReceiptApi'
import {message} from 'ant-design-vue'
import WaveSurferAudio from '@/components/AudioView/waveSurferAudio.vue'
import ChatWindow from '@/views/qc/voice/dynamicChat/ChatWindow.vue'

// ===========================================DATA======================================================
const curMsgId = ref(null) //当前播放的消息id
const chatWindowRef = ref()
const chatLoading = ref(false)
const manualCheck = tool.dictList('ManualCheck')
const isAbnormaled = ref(false) //是否违规
const isQualityRole = tool.data.get('USER_INFO').roleCodeList.includes('qualityInspector') //是否质检角色
let checkFormRef = ref()
let voiceStatus = ref('') //质检状态
let modalOpen = ref(false) //质检异常弹框
let formState = ref({
	inspection: null,
	remark: null,
	id: null,
	callId: null,
	agentNum: null,
	userName: null,
	caller: null,
	callee: null,
	companyName: null,
	qcInspector: tool.data.get('USER_INFO').id,
	callDuration: null
})
let rules = ref({
	inspection: [{required: true, message: '请选择违规类型', trigger: ['change', 'blur']}],
	remark: [{required: true, message: '请输入违规详情', trigger: ['change', 'blur']}]
})
// 在父组件中调用示例
const messageListRef = ref(null)
// 模拟数据
const currentUser = reactive({
	id: 1,
	name: '客服',
	avatar: new URL('@/assets/images/service_avatar.png', import.meta.url).href
})

const targetUser = reactive({
	id: 2,
	name: '客户',
	avatar: new URL('@/assets/images/customer_avatar.png', import.meta.url).href
})

const messages = ref([])
const callId = ref()

const callTypeOptions = tool.dictList('TalkType')

const props = defineProps({
	viewType: String,
	caseId: String
})
const searchFormRef = ref()
const searchFormState = ref({
	current: 1,
	size: 5,
	caseId: props.caseId,
	caller: undefined,
	callee: undefined,
	userName: undefined,
	taskId: undefined,
	callDuration: undefined,
	beginTime: props.viewType === 'total' ? dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss') : undefined,
	endTime: props.viewType === 'total' ? dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss') : undefined,
	deptId: undefined
})
const treeData = ref([])
const treeDefaultExpandedKeys = ref([])
const tableRef = ref()
const columns = [
	{
		title: '通话类型',
		dataIndex: 'callTypeName'
	},
	{
		title: '呼叫序列号',
		dataIndex: 'callId'
	},
	{
		title: '主叫',
		dataIndex: 'caller'
	},
	{
		title: '被叫',
		dataIndex: 'callee'
	},
	{
		title: '任务ID',
		dataIndex: 'taskId'
	},
	{
		title: '彩铃识别',
		dataIndex: 'asrName',
		slots: {customRender: 'asrName'}
	},
	{
		title: '坐席',
		dataIndex: 'agentNum'
	},
	{
		title: '坐席姓名',
		dataIndex: 'userName'
	},
	{
		title: '质检结果',
		dataIndex: 'qcResult',
		customRender: (param) => {
			const find = manualCheck.find((item) => item.value == param.text)
			return find ? find.label : ''
		}
	},
	{
		title: '通话开始时间',
		dataIndex: 'startTime'
	},
	{
		title: '通话结束时间',
		dataIndex: 'endTime'
	},
	{
		title: '通话时长',
		dataIndex: 'callDuration'
	},
	{
		title: '号码归属地',
		dataIndex: 'area'
	},
	{
		title: '呼叫结果',
		dataIndex: 'result'
	},
	{
		title: '是否坐席挂断',
		dataIndex: 'signal',
		slots: {customRender: 'signal'}
	},
	{
		title: '话单回传时间',
		dataIndex: 'createdTime'
	},
	{
		title: '通话录音',
		dataIndex: 'fileUrl',
		fixed: 'right',
		align: 'center'
	}
]
const visible = ref(false)
const audioUrl = ref('')
const isStop = ref(false)
const createTimeArr = ref([dayjs().startOf('day'), dayjs().endOf('day')])
const pageOptions = {
	size: props.viewType === 'total' ? 10 : 5,
	sizeOptions: props.viewType === 'total' ? [] : ['5', '10', '20']
}
let curRowInfo = ref({})
// ===========================================LIFECYCLE HOOKS===========================================
onMounted(() => {
	bizUserApi.userOrgTreeSelector().then((res) => {
		if (res !== null) {
			treeData.value = res
			// 默认展开2级
			treeData.value.forEach((item) => {
				// 因为0的顶级
				if (item.parentId === '0') {
					treeDefaultExpandedKeys.value.push(item.id)
					// 取到下级ID
					if (item.children) {
						item.children.forEach((items) => {
							treeDefaultExpandedKeys.value.push(items.id)
						})
					}
				}
			})
		}
	})
})
// ===========================================METHODS==================================================
const onClose = () => {
	visible.value = false
	isStop.value = true
	setTimeout(() => {
		isStop.value = false
	}, 500)
	voiceStatus.value = ''
	modalOpen.value = false
	curMsgId.value = null
}
const dateChange = (value) => {
	searchFormState.value.beginTime = value[0].format('YYYY-MM-DD').concat(' 00:00:00')
	searchFormState.value.endTime = value[1].format('YYYY-MM-DD').concat(' 23:59:59')
}
const reset = () => {
	searchFormRef.value.resetFields()
	createTimeArr.value = [dayjs().startOf('day'), dayjs().endOf('day')]
	searchFormState.value.beginTime = dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss')
	searchFormState.value.endTime = dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss')
}
// 质检状态改变
const voiceStatusChange = (e) => {
	if (e.target.value === 'abnormal') {
		modalOpen.value = true
		isAbnormaled.value = false
	} else {
		manualCheckSubmit(e.target.value)
	}
}
//已经质检违规后查看详情
const abnormalCheck = () => {
	isAbnormaled.value = true
	modalOpen.value = true
}
const okModal = () => {
	checkFormRef.value
		.validate()
		.then(() => {
			manualCheckSubmit(voiceStatus.value)
			checkFormRef.value.resetFields()
			modalOpen.value = false
		})
		.catch(() => {
			message.error('请完善违规信息')
		})
}
const cancelModal = (e) => {
	voiceStatus.value = ''
	checkFormRef.value.resetFields()
}
//录音时间更新
const handleTimeUpdate = (curTime) => {
	if (!messages.value.length) return
	// console.log('messages', messages.value)

	// 将当前时间转换为mm:ss格式用于比较
	const minutes = Math.floor(curTime / 60000)
	const seconds = Math.floor((curTime % 60000) / 1000)
	const currentTimeString = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
	// 找到当前时间对应的消息
	let foundMessage = null
	for (let i = 0; i < messages.value.length; i++) {
		// 比较时间字符串，找到小于等于当前播放时间的最新消息
		if (messages.value[i].timeOffset <= currentTimeString) {
			foundMessage = messages.value[i]
		} else {
			// 如果找到了大于当前时间的消息，说明前一条是我们要找的
			break
		}
	}
	// console.log('foundMessage', foundMessage)

	// 如果找到了对应消息，设置当前消息ID
	if (foundMessage) {
		// 只有当ID变化时才更新，避免不必要的重渲染
		if (curMsgId.value !== foundMessage.id) {
			curMsgId.value = foundMessage.id
			// 滚动到当前消息
			if (chatWindowRef.value) {
				chatWindowRef.value.scrollToMessage(foundMessage.id)
			}
		}
	}
}
// ===========================================REQUEST==================================================
const loadData = (parameter) => {
	searchFormState.value.current = parameter.current
	searchFormState.value.size = parameter.size
	return callReceiptApi.pageList(searchFormState.value).then((res) => {
		return res
	})
}
const toPlay = (record) => {
	curRowInfo.value = record
	Object.keys(formState.value).forEach((key) => {
		if (record[key] !== undefined) {
			formState.value[key] = record[key]
		}
	})
	visible.value = true

	audioUrl.value = record.fileUrl
	//获取质检状态
	manualCheckApi.getStatus(record.callId).then((res) => {
		if (!res.inspection) {
			voiceStatus.value = ''
			isAbnormaled.value = false
			return
		}
		if (res.inspection !== '2') {
			voiceStatus.value = 'abnormal'
		} else {
			voiceStatus.value = 'normal'
		}
		formState.value.inspection = res.inspection
		formState.value.remark = res.remark
	})
	//获取聊天内容
	chatLoading.value = true
	voiceTextApi
		.getTextByCallId(record.callId)
		.then((res) => {
			chatLoading.value = false
			messages.value = []

			// 计算对话的起始和结束时间
			// const startTime = new Date(testData[0].chatTime).getTime()
			// testData.forEach((item) => {
			// 	// 计算当前消息相对于起始时间的偏移（毫秒）
			// 	const messageTime = new Date(item.chatTime).getTime()
			// 	const offsetMs = messageTime - startTime

			// 	// 转换为mm:ss格式
			// 	const minutes = Math.floor(offsetMs / 60000)
			// 	const seconds = Math.floor((offsetMs % 60000) / 1000)
			// 	const timeString = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
			// 	messages.value.push({
			// 		id: item.id,
			// 		content: item.content,
			// 		timestamp: item.chatTime,
			// 		isSelf: item.speakerRole === 2,
			// 		timeOffset: timeString
			// 	})
			// })

			// 计算对话的起始和结束时间
			const startTime = new Date(res[0].chatTime).getTime()
			res.forEach((item) => {
				// 计算当前消息相对于起始时间的偏移（毫秒）
				const messageTime = new Date(item.chatTime).getTime()
				const offsetMs = messageTime - startTime

				// 转换为mm:ss格式
				const minutes = Math.floor(offsetMs / 60000)
				const seconds = Math.floor((offsetMs % 60000) / 1000)
				const timeString = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
				messages.value.push({
					id: item.id,
					content: item.content,
					timestamp: item.chatTime,
					isSelf: item.speakerRole === 2,
					timeOffset: timeString
				})
			})
		})
		.catch(() => {
			chatLoading.value = false
		})
}
//质检结果提交
const manualCheckSubmit = (status) => {
	if (status === 'normal') {
		formState.value.inspection = null
		formState.value.remark = null
	}
	manualCheckApi.insert(formState.value).then((res) => {
		message.success('操作成功')
		tableRef.value.refresh(true)
	})
}
</script>
<style lang="less" scoped>
.call-autio {
	display: flex;
	justify-content: space-between;
	align-items: center;
	width: 100%;
	border-bottom: 1px solid #e6e6e6;

	.voice {
		flex: 1;
	}

	.btn {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		margin-left: 15px;
	}
}

:deep(.ant-picker-range) {
	width: 100%;
}

.icon-buhege,
.icon-hege {
	font-size: 40px;
}

.call-chat {
	height: calc(100vh - 400px);

	.message-list {
		min-height: calc(100vh - 240px);
		height: calc(100vh - 240px);
	}
}
</style>
